package yf.mall.controller.api.app;

import com.yf.annotation.LoginUserId;
import com.yf.entity.TokenEntity;
import com.yf.response.R;
import com.yf.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import yf.mall.entity.UserEntity;
import yf.mall.service.UserService;
import yf.mall.vo.app.common.DataResult;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


public abstract class ApiAppBaseController {

    @Value("${yf.token.header}")
    public String LOGIN_TOKEN_KEY;

    @Resource
    private TokenService tokenService;

    @Resource
    private UserService userService;

    public Long getLoginUser(HttpServletRequest request) {
        String token = request.getHeader(this.LOGIN_TOKEN_KEY);
        TokenEntity tokenEntity = null;
        try {
            tokenEntity = this.tokenService.validateToken(token);
            return tokenEntity.getUserId();
        } catch (Exception e) {
            return null;
        }
    }

    public UserEntity getLoginUser(Long loginUserId) {
        return userService.get(loginUserId);
    }

    public R jsonDataResult(String json) {
        return R.ok(new DataResult(true, json, true));
    }

    public R dataResult(Object o) {
        return R.ok(new DataResult(true, o));
    }
}
